<template>
  <div class="page-main"  v-title :data-title="dataTitle?dataTitle:'报工单详情'">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container">
      <div class="head-content">
        <span class="bold-font">报工单详情</span>
        <div class="btn-line">
          <a-button @click="handleSave" class="hte-btn add-btn" type="primary">保存</a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm">
          <section>
            <div class="section-header">报工单信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="报工单编号：">
                  <a-input
                    disabled
                    :value="
                      project.busKey && project.itemCount
                        ? project.busKey + '(' + (project.itemCount + 1) + '/' + (project.itemCount + 1) + ')'
                        : ''
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工类别：">
                  <a-select disabled default-value="0" style="width: 100%">
                    <a-select-option v-for="(code, index) in codes.WorkReportType" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工状态：">
                  <a-select disabled v-model="task.status">
                    <a-select-option
                      v-for="(code, index) in codes.WorkReportTaskStatus"
                      :value="code.code"
                      :key="index"
                    >
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同编号：">
                  <a-input disabled v-model="project.contractNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="合同名称：">
                  <a-input disabled v-model="project.contractName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目负责人：">
                  <UserInputSelector
                    :username.sync="task.handlerUserId"
                    :realname.sync="task.handlerUser"
                    multiple="multiple"
                    placeholder="请选择"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="供应商名称">
                  <a-input disabled v-model="project.supplierName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同金额：">
                  <a-input disabled v-model="project.amount" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item ref="nodeContent" label="工期节点内容：" prop="nodeContent">
                  <a-input v-model="task.nodeContent" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="关联节点金额：">
                  <a-input v-model="task.paymentAmount" />
                </a-form-model-item>
              </a-col>

              <a-col :span="16">
                <a-form-model-item label="付款节点内容：" prop="paymentContent">
                  <a-input v-model="task.paymentContent" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="PO单行号：">
                  <a-input
                    v-model="task.poLine"
                    :suffix="'共' + (project.poLineCount ? project.poLineCount : '0') + '行'"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="费用支出号">
                  <a-input placeholder="自动带入" v-model="task.costNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="提交资料内容：">
                  <a-input v-model="task.submitResource" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同约定日期：">
                  <a-date-picker style="width: 100%" valueFormat="YYYY-MM-DD" v-model="task.complateTime" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工节点标志：">
                  <div style="display: flex; justify-content: space-around">
                    <a-select v-model="task.nodeIdentify" style="width: 100%">
                      <a-select-option v-for="(code, index) in contractNodeOptions" :key="index" :value="code">
                        {{ code }}
                      </a-select-option>
                    </a-select>
                    <div style="display: flex; width: 20vw; justify-content: flex-end">
                      <span style="min-width: 60px; text-align: right; padding-right: 5px; line-height: 40px"
                        >税率:</span
                      >
                      <a-input placeholder="" v-model="task.taxRate" :suffix="'%'" />
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="付款节点标志：">
                  <div style="display: flex; justify-content: space-around">
                    <a-select v-model="task.isPayNode" style="width: 100%">
                      <a-select-option v-for="(code, index) in yesOrNo" :key="index" :value="code.code">
                        {{ code.name }}
                      </a-select-option>
                    </a-select>
                    <div style="display: flex; width: 60vw; justify-content: flex-end">
                      <span style="min-width: 110px; text-align: right; padding-right: 5px; line-height: 40px"
                        >多个付款条件:</span
                      >
                      <a-select v-model="task.isMutiContiditon" style="width: 100%">
                        <a-select-option v-for="(code, index) in yesOrNo" :key="index" :value="code.code">
                          {{ code.name }}
                        </a-select-option>
                      </a-select>
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <ResultABox :task.sync="task" ref="resultABoxRef" />
          <ResultBBox :task.sync="task" ref="resultBBoxRef" />
        </a-form-model>
      </div>
    </div>
    <UserSelector :show="showUserSelector" :muti="false" @selected="selectUser" />
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ResultABox: () => import('@/views/workReport/task/ResultAAdd'),
    ResultBBox: () => import('@/views/workReport/task/ResultBAdd'),
    PaymentList: () => import('@/views/workReport/task/TaskDetail_PaymentList'),
    QualityList: () => import('@/views/workReport/task/TaskDetail_QualityList'),
    SettlementDetail: () => import('@/views/workReport/util/SettlementDetail'),
    UserSelector: () => import('@/views/workReport/role/UserSelector'),
  },
  data() {
    return {
      dataTitle:this.$route?this.$route.name:"",
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      projectId: this.$route.query && this.$route.query.projectId,
      project: {},
      task: { result0: {}, result1: {} },
      yesOrNo: [
        { code: '1', name: '是' },
        { code: '0', name: '否' },
      ],
      urls: {
        project: '/workReport/project/info',
        saveTask: '/workReport/task/save',
        codes: '/manage/codeInfo/queryByTypes',
        psCodes: '/hte/contract/codes',
        myPermission: '/workReport/project/myPermission',
        paymentList: '/workReport/payment/page',
        personList: '/person/info/personList',
      },

      result: {},
      codes: {},
      showUserSelector: false,
      contractNodeOptions: ['到货', '安装', '验收', '质保'],
      permission: [],
      showPaymentList: false,
      visiblePayment: false,
      showQualityList: false,
      visibleQuality: false,
      showSettlementDetail: false,
      personMap: [],
      existPersonMap: [],
      personList: [],
      selectUserKeyWord: null,
      selectUserTimeOut: null,
    }
  },
  mounted() {
    this.fetchProject()
    this.fetchCodes()
    this.fetchPsCodes()
  },
  methods: {
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: this.task.projectId }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchPsCodes() {
      postAction(this.urls.psCodes, { codes: ['contract_status'] }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    fetchCodes() {
      getAction(this.urls.codes, { types: 'WorkReportTaskStatus,WorkReportType,WorkReportTaskPaymentStatus' }).then(
        (res) => {
          if (res.success) {
            this.codes = { ...this.codes, ...res.result }
          }
        }
      )
    },
    fetchProject() {
      getAction(this.urls.project + '/' + this.projectId, {}).then((res) => {
        if (res.success) {
          this.project = res.result
          if (this.project.costNumber) {
            let costNumber = this.project.costNumber.split(',')
            if (costNumber.length > 0 && costNumber[0] != 'null') {
              this.$set(this.task, 'costNumber', costNumber[0] ? costNumber[0] : '')
            }
          }
        }
      })
    },
    handleSave() {
      let partaAttachs = this.$refs.resultABoxRef.getAttachs()
      let partbAttachs = this.$refs.resultBBoxRef.getAttachs()
      this.task.partaAttachs = Array.isArray(partaAttachs)?partaAttachs:[partaAttachs]
      this.task.partbAttachs = Array.isArray(partbAttachs)?partbAttachs:[partbAttachs]
      if (this.task.partaStatus == '2' && !this.task.partaActualTime) {
        return this.$messageWorkReport.warning('请输入实际完成时间')
      }
      if (!this.task.partaStatus && this.task.partaActualTime) {
        return this.$messageWorkReport.warning('请选择节点报工完成情况')
      }
      if (this.task.partaResult == '质量合格' && !this.task.partaAcceptTime) {
        return this.$messageWorkReport.warning('请输入现场验收时间')
      }
      if (!this.task.partaResult && this.task.partaAcceptTime) {
        return this.$messageWorkReport.warning('请选择节点报工质量情况')
      }
      if(this.task.partaStatus!=2 && this.task.partaResult != '质量合格' && this.task.partaNodeStatus == '逾期'){
        if(!this.task.partaPlanTime){
          return this.$messageWorkReport.warning('逾期不完成且质量合格，请输入计划完成时间')
        }
      }
      if (this.task.partaStatus != '2') {
        if (this.task.partaNodeStatus == '逾期') {
          if (!this.task.partaPlanTime || !this.task.partaDelayReason || !this.task.partaDelayRemark) {
            return this.$messageWorkReport.warning(
              '当【工期状态】=逾期，需要填写【预计完成日期】、【逾期责任方】、【逾期具体原因】'
            )
          }
        }
        if (this.task.partaPlanTime && (!this.task.partaDelayReason || !this.task.partaDelayRemark)) {
          return this.$messageWorkReport.warning(
            '当【工期状态】=逾期，需要填写【预计完成日期】、【逾期责任方】、【逾期具体原因】'
          )
        }
      }
      if (!this.task.complateTime) {
        return this.$messageWorkReport.warning('请输入合同约定时间')
      }
      if (this.task.partaStatus == '1') {
        if (this.task.partaNodeStatus == '逾期') {
          if (!this.task.partaPlanTime) {
            return this.$messageWorkReport.warning('请填写预计完成日期')
          }
          if (!this.task.partaDelayReason) {
            return this.$messageWorkReport.warning('请选择逾期责任方')
          }
          if (!this.task.partaDelayRemark) {
            return this.$messageWorkReport.warning('请选择逾期具体原因')
          }
        }
        if (this.task.partaResult == '质量合格') {
          return this.$messageWorkReport.warning('请勿选择[质量合格]')
        }
      }
      if (this.task.partaStatus == '2') {
        if (!this.task.partaActualTime) {
          return this.$messageWorkReport.warning('请填写实际完成时间')
        }
        if (this.task.partaNodeStatus == '逾期') {
          if (!this.task.partaDelayReason) {
            return this.$messageWorkReport.warning('请选择逾期责任方')
          }
          if (!this.task.partaDelayRemark) {
            return this.$messageWorkReport.warning('请选择逾期具体原因')
          }
        }
      }
      if (this.task.partaResult == '质量合格') {
        if (!this.task.partaAcceptTime) {
          return this.$messageWorkReport.warning('请输入现场验收时间')
        } else {
          var acceptTime = new Date(this.task.partaAcceptTime).getTime()
          var actualTime = new Date(this.task.partaActualTime).getTime()
          if (acceptTime < actualTime) {
            return this.$messageWorkReport.warning('现场验收时间必须晚于或等于实际完成时间')
          }
        }
        if (this.task.nodeIdentify == '验收' || this.task.isPayNode == '1') {
          if (partaAttachs) {
            let hasAcceptFile = false
            partaAttachs.forEach((attach) => {
              if (attach.fileName && attach.fileName.indexOf('验收') > -1) {
                hasAcceptFile = true
              }
            })
            if (!hasAcceptFile) {
              return this.$messageWorkReport.warning('请上传验收单附件')
            }
          } else {
            return this.$messageWorkReport.warning('请上传验收单附件')
          }
        }
      }
      this.$set(this.task, 'projectId', this.projectId)
      postAction(this.urls.saveTask, this.task).then((res) => {
        if (res.success) {
          this.$messageWorkReport.success('保存成功')
          let urlJump = this.$router.resolve({ path:'/workReport/taskDetail/' + res.result.id })
          window.open(urlJump.href, '_blank')
        } else {
          this.$messageWorkReport.error('保存失败:' + res.message)
        }
      })
    },
    openUserSelector() {
      this.showUserSelector = true
    },
    selectUser(selection) {
      if (selection.length > 0) {
        this.$set(this.task, 'handlerUserId', selection[0].username.trim())
        this.$set(this.task, 'handlerUser', selection[0].realname.trim())
      }
      this.showUserSelector = false
    },
    toContractAttach() {
      let urlJump = this.$router.resolve({ path:'/workReport/attach/' + this.project.id })
      window.open(urlJump.href, '_blank')
    },
    clickPersonSelector(type, mutil) {
      this.currentType = type
      this.mutil = mutil
      let usernames = this.task[type + 'Id'] ? this.task[type + 'Id'].split(',') : []
      let realnames = this.task[type] ? this.task[type].split(',') : []
      for (let i = 0; i < realnames.length; i++) {
        this.$set(this.existPersonMap, realnames[i], usernames[i])
      }
    },
    fetchUserList(value) {
      if (this.selectUserTimeOut) {
        window.clearTimeout(this.selectUserTimeOut)
      }
      this.selectUserTimeOut = window.setTimeout(this.toFetchUserList, 800)
      this.selectUserKeyWord = value
    },
    async toFetchUserList(value) {
      let param = {}
      param.keyword = this.selectUserKeyWord
      param.pageSize = 100
      let res = await postAction(this.urls.personList, param)
      if (res.success) {
        this.personList = res.result.records
        this.personList.forEach((p) => {
          this.$set(this.personMap, p.username, p.realname)
        })
      }
    },
    selectUserList(selected) {
      if (this.mutil == '1') {
        let usernames = []
        let realnames = []
        selected.forEach((s) => {
          if (s.indexOf('new_') > -1) {
            let username = s.split('_')[1]
            let realname = this.personMap[username]
            if (username && realname && usernames.indexOf(username) <= -1) {
              usernames.push(username)
              realnames.push(this.personMap[username])
            }
          } else {
            let realname = s
            let username = this.existPersonMap[realname]
            if (username && realname && usernames.indexOf(username) <= -1) {
              usernames.push(username)
              realnames.push(s)
            }
          }
        })
        this.$set(this.task, this.currentType + 'Id', usernames.join(','))
        this.$set(this.task, this.currentType, realnames.join(','))
      } else {
        if (selected) {
          if (selected.indexOf('new_') > -1) {
            let username = selected.split('_')[1]
            let realname = this.personMap[username]
            if (username && realname) {
              this.$set(this.task, this.currentType + 'Id', username)
              this.$set(this.task, this.currentType, this.personMap[username])
            }
          } else {
            let username = selected
            let realname = this.existPersonMap[username]
            if (username && realname) {
              this.$set(this.task, this.currentType + 'Id', selected)
              this.$set(this.task, this.currentType, this.existPersonMap[selected])
            }
          }
        } else {
          this.$set(this.task, this.currentType + 'Id', '')
          this.$set(this.task, this.currentType, '')
        }
      }
    },
    calcTaskStatus(resultA, resultB) {
      let taskResultMap = {}
      taskResultMap['0000'] = '0' //甲未报工，乙未报工
      taskResultMap['0010'] = '1' //甲未报工，乙报完成
      taskResultMap['0011'] = '2' //甲未报工，乙报合格
      taskResultMap['1000'] = '3' //甲报完成，乙未报工
      taskResultMap['1010'] = '4' //甲报完成，乙报完成
      taskResultMap['1011'] = '5' //甲报完成，乙报合格
      taskResultMap['1100'] = '6' //甲报合格，已未报工
      taskResultMap['1110'] = '7' //甲报合格，乙报完成
      taskResultMap['1111'] = '8' //甲报合格，乙报合格
      let resultMap = {}
      resultMap['质量不合格'] = '10'
      resultMap['质量合格'] = '11'
      let prefix = '00'
      let suffix = '00'
      if (resultMap[resultA]) {
        prefix = resultMap[resultA]
      }
      if (resultMap[resultB]) {
        suffix = resultMap[resultB]
      }
      let key = prefix + suffix
      let taskStatus = taskResultMap[key]
      return taskStatus
    },
  },
  watch: {
    'task': {
      handler(newV, oldV) {
        this.$set(this.task, 'status', this.calcTaskStatus(this.task.partaResult, this.task.partbResult))
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .container {
    .content {
      margin-top: 20px;
      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  .tips-box {
    margin-top: 32px;
    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}
.icon-file {
  background-image: url('~@assets/file.png');
}
.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
